package com.stlcctv.POSSender;

import android.util.Log;

public class CommandComposer 
{
	public static final String DEBUG_TAG = "POSSender";
	
	public static final byte CMD_CODE_ALIVE_CHECK 		= 0x0;
	public static final byte CMD_CODE_POS_DATA 			= 0x01;
	public static final byte CMD_CODE_TRANSACTION_START	= 0x02;
	public static final byte CMD_CODE_DISPLAY_CLEAR 	= 0x04;
	
	public byte m_StartCode;
	public byte m_CmdClass;
	public byte m_CmdCode;
	public byte m_CRC;
	public byte m_FinishCode;
	
	public CommandComposer()
	{
		m_StartCode = (byte) 0xAA;
		m_CmdClass 	= 0xB;
		m_CmdCode	= 0;
		m_CRC		= 0;
		m_FinishCode= (byte) 0xEE;
	}

	public int MakeCommand_Simple(byte[] cmd)
	{
		int pos = 0;
		
		cmd[pos] = m_StartCode; 							pos++;
		cmd[pos] = m_CmdClass; 		m_CRC = m_CmdClass;		pos++;
		cmd[pos] = m_CmdCode; 		m_CRC ^= m_CmdCode;		pos++;
		ByteArrayUtil.ShortToByte(cmd, pos, (short) 0x02); m_CRC ^= 0x02;	pos += 2;
		cmd[pos] = m_CmdClass; 		m_CRC ^= m_CmdClass;	pos++;
		cmd[pos] = m_CmdCode; 		m_CRC ^= m_CmdCode;		pos++;
		cmd[pos] = m_CRC; 									pos++;
		cmd[pos] = m_FinishCode; 							pos++;
		
		return pos;
	}
	public int MakeCommand_POSSend(byte[] cmd,String strPosData, short data_len)
	{
		int pos = 0;

		cmd[pos] = m_StartCode; 	pos++; 
		cmd[pos] = m_CmdClass; 		pos++; 
		cmd[pos] = m_CmdCode; 		pos++; 
		ByteArrayUtil.ShortToByte(cmd, pos, data_len); 		pos += 2;
		ByteArrayUtil.StringToByte(cmd, pos, strPosData); 	pos += data_len;
		
		//Log.i(DEBUG_TAG, "pos : " + pos + ", data_len : " + data_len);
		byte send_crc = 0;
		for(int i = 1; i < pos ; i++) 
		{
			//Log.i(DEBUG_TAG, "data : " + cmd[i] );
			send_crc ^= cmd[i];		
		}
		//Log.i(DEBUG_TAG, "send crc : " + send_crc);
		cmd[pos] = send_crc; 		pos++;
		cmd[pos] = m_FinishCode; 	pos++;
		
		return pos;
	}
}
